import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:hiot_cloud_app_v1/app/constants/enums/device_type.dart';
import 'package:hiot_cloud_app_v1/app/routes/app_routes.dart';
import 'package:hiot_cloud_app_v1/app/modules/device/controllers/device_list_controller.dart';
import 'package:hiot_cloud_app_v1/app/config/themes/app_colors.dart';
import 'package:hiot_cloud_app_v1/app/config/themes/app_text_styles.dart';

class DeviceListView extends GetView<DeviceListController> {
  const DeviceListView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('我的设备'),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.search),
            onPressed: () => _showSearchDialog(context),
          ),
        ],
      ),
      body: Obx(() => _buildBody()),
      floatingActionButton: FloatingActionButton(
        onPressed: () => Get.toNamed(AppRoutes.addDevice),
        backgroundColor: AppColors.primary,
        child: const Icon(Icons.add),
      ),
    );
  }

  Widget _buildBody() {
    if (controller.isLoading.value) {
      return const Center(child: CircularProgressIndicator());
    }

    if (controller.errorMessage.isNotEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const Icon(
              Icons.error_outline,
              size: 60,
              color: AppColors.error,
            ),
            const SizedBox(height: 16),
            Text(
              '加载失败',
              style: AppTextStyles.titleMediumLight,
            ),
            const SizedBox(height: 8),
            Text(
              controller.errorMessage.value,
              style: AppTextStyles.bodyMediumLight,
              textAlign: TextAlign.center,
            ),
            const SizedBox(height: 24),
            ElevatedButton(
              onPressed: controller.loadDevices,
              child: const Text('重试'),
            ),
          ],
        ),
      );
    }

    if (controller.devices.isEmpty) {
      return _buildEmptyState();
    }

    return RefreshIndicator(
      onRefresh: controller.refreshDevices,
      child: ListView(
        padding: const EdgeInsets.all(16),
        children: [
          _buildDeviceGroups(),
          const SizedBox(height: 24),
          _buildDeviceList(),
        ],
      ),
    );
  }

  Widget _buildEmptyState() {
    return Center(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          const Icon(
            Icons.devices_other,
            size: 80,
            color: Colors.grey,
          ),
          const SizedBox(height: 24),
          Text(
            '暂无设备',
            style: AppTextStyles.titleMediumLight,
          ),
          const SizedBox(height: 16),
          Text(
            '点击右下角按钮添加设备',
            style: AppTextStyles.bodyMediumLight.copyWith(color: Colors.grey),
          ),
          const SizedBox(height: 32),
          ElevatedButton(
            onPressed: () => Get.toNamed(AppRoutes.addDevice),
            child: const Text('添加设备'),
          ),
        ],
      ),
    );
  }

  Widget _buildDeviceGroups() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 4, bottom: 16),
          child: Text(
            '设备分组',
            style: AppTextStyles.titleMediumLight,
          ),
        ),
        SizedBox(
          height: 40,
          child: ListView.builder(
            scrollDirection: Axis.horizontal,
            itemCount: controller.deviceGroups.length,
            itemBuilder: (context, index) {
              final group = controller.deviceGroups[index];
              final isSelected = group == controller.selectedGroup.value;
              
              return Padding(
                padding: const EdgeInsets.only(right: 12),
                child: ChoiceChip(
                  label: Text(group),
                  selected: isSelected,
                  selectedColor: AppColors.primary,
                  labelStyle: TextStyle(
                    color: isSelected ? Colors.white : Colors.black,
                  ),
                  onSelected: (selected) {
                    controller.selectGroup(group);
                  },
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildDeviceList() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 4, bottom: 16),
          child: Text(
            '设备列表',
            style: AppTextStyles.titleMediumLight,
          ),
        ),
        ...controller.filteredDevices.map((device) => _buildDeviceCard(device)),
      ],
    );
  }

  Widget _buildDeviceCard(dynamic device) {
    final bool isOnline = device.status == DeviceStatus.online;
    
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      elevation: 2,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        borderRadius: BorderRadius.circular(12),
        onTap: () => controller.openDeviceDetail(device),
        child: Padding(
          padding: const EdgeInsets.all(16),
          child: Column(
            children: [
              Row(
                children: [
                  _buildDeviceIcon(device.type),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          device.name,
                          style: AppTextStyles.titleSmallLight,
                        ),
                        const SizedBox(height: 4),
                        Text(
                          device.type.toReadableString(),
                          style: AppTextStyles.bodySmallLight,
                        ),
                      ],
                    ),
                  ),
                  Container(
                    padding: const EdgeInsets.symmetric(
                      horizontal: 8,
                      vertical: 4,
                    ),
                    decoration: BoxDecoration(
                      color: isOnline
                          ? AppColors.deviceOnline.withOpacity(0.1)
                          : AppColors.deviceOffline.withOpacity(0.1),
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Row(
                      mainAxisSize: MainAxisSize.min,
                      children: [
                        Container(
                          width: 8,
                          height: 8,
                          decoration: BoxDecoration(
                            color: isOnline
                                ? AppColors.deviceOnline
                                : AppColors.deviceOffline,
                            shape: BoxShape.circle,
                          ),
                        ),
                        const SizedBox(width: 4),
                        Text(
                          isOnline ? '在线' : '离线',
                          style: AppTextStyles.bodySmallLight.copyWith(
                            color: isOnline
                                ? AppColors.deviceOnline
                                : AppColors.deviceOffline,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              const Divider(height: 1),
              const SizedBox(height: 12),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  _buildActionButton(
                    icon: Icons.power_settings_new,
                    label: isOnline ? '关闭' : '开启',
                    onTap: () => controller.toggleDevice(device),
                  ),
                  _buildActionButton(
                    icon: Icons.settings,
                    label: '设置',
                    onTap: () => controller.openDeviceSettings(device),
                  ),
                  _buildActionButton(
                    icon: Icons.timeline,
                    label: '数据',
                    onTap: () => controller.openDeviceData(device),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildDeviceIcon(DeviceType type) {
    IconData iconData;
    Color iconColor;

    switch (type) {
      case DeviceType.lightingController:
        iconData = Icons.lightbulb;
        iconColor = Colors.amber;
        break;
      case DeviceType.temperatureSensor:
      case DeviceType.humiditySensor:
        iconData = Icons.thermostat;
        iconColor = Colors.blue;
        break;
      case DeviceType.camera:
        iconData = Icons.videocam;
        iconColor = Colors.red;
        break;
      case DeviceType.switchController:
        iconData = Icons.toggle_on;
        iconColor = Colors.green;
        break;
      case DeviceType.gateway:
        iconData = Icons.router;
        iconColor = Colors.purple;
        break;
      default:
        iconData = Icons.devices_other;
        iconColor = Colors.grey;
    }

    return Container(
      width: 48,
      height: 48,
      decoration: BoxDecoration(
        color: iconColor.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Icon(
        iconData,
        color: iconColor,
        size: 28,
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
  }) {
    return InkWell(
      onTap: onTap,
      borderRadius: BorderRadius.circular(8),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(
              icon,
              color: AppColors.primary,
              size: 20,
            ),
            const SizedBox(height: 4),
            Text(
              label,
              style: AppTextStyles.bodySmallLight,
            ),
          ],
        ),
      ),
    );
  }

  void _showSearchDialog(BuildContext context) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('搜索设备'),
        content: TextField(
          decoration: const InputDecoration(
            hintText: '输入设备名称、ID或类型',
            prefixIcon: Icon(Icons.search),
          ),
          onChanged: controller.searchDevices,
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
} 